package xyz.xtt.schedule.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import xyz.xtt.schedule.entity.TblLuckPhoneEntitlementDeliver;
import xyz.xtt.schedule.mapper.equity.TblLuckPhoneEntitlementDeliverMapper;
import xyz.xtt.schedule.support.GomeLuckPhoneHttpService;
import xyz.xtt.schedule.utils.RedisLockUtil;

/**
 * 靓号兑换订单底层服务
 *
 * @author dale
 * @since 2024/12/31
 **/
@Service
@Slf4j
public class LuckPhoneEntitlementDeliverService extends ServiceImpl<TblLuckPhoneEntitlementDeliverMapper, TblLuckPhoneEntitlementDeliver> {
	@Autowired
	private GomeLuckPhoneHttpService gomeLuckPhoneHttpService;
	@Autowired
	RedisLockUtil redisLockUtil;

	private static final String LOCK_KEY_REFRESH_PHONE_ORDER_STATUS_FMT = "NFT:LOCK:REFRESH:PHONE:ORDER:STATUS";
	private static final long ONE_WEEK_MILLISECONDS = 1000 * 60 * 60 * 24 * 7L;

	/**
	 * 更新 LuckPhoneOrderStatus
	 */

	public void updateLuckPhoneOrderStatus() {
		log.info("开始执行靓号池订单状态检查任务");
		String lockKey = LOCK_KEY_REFRESH_PHONE_ORDER_STATUS_FMT;
		String lockValue = UUID.randomUUID().toString();
		boolean locked = redisLockUtil.tryLock(lockKey, lockValue, 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);
		if (locked) {
			try {
				// 分页查询需要更新状态的订单
				int current = 1;
				Page<TblLuckPhoneEntitlementDeliver> page = new Page<>(current, 10);
				QueryWrapper<TblLuckPhoneEntitlementDeliver> wrapper = new QueryWrapper<>();
				wrapper.eq("is_valid", 1);
				wrapper.in("order_status", 0, 1, 9, 10, 99);
				wrapper.gt("update_time", System.currentTimeMillis() - ONE_WEEK_MILLISECONDS);
				Page<TblLuckPhoneEntitlementDeliver> pageResult;
				Map<String, Integer> statistics = new HashMap<>();
				statistics.put("update", 0);
				do {
					pageResult = baseMapper.selectPage(page, wrapper);
					handleOrderStatus(pageResult.getRecords(), statistics);
					page.setCurrent(page.getCurrent() + 1);
				} while (pageResult.getRecords().size() > 0);
				log.info("updateLuckPhoneOrderStatus: 批量操作完成，更新{}条", statistics.get("update"));
			} finally {
				redisLockUtil.releaseLock(lockKey, lockValue);
			}
		} else {
			log.info("updateLuckPhoneOrderStatus 获取锁失败");
		}
	}

	private void handleOrderStatus(List<TblLuckPhoneEntitlementDeliver> records, Map<String, Integer> statistics) {
		if (CollectionUtils.isEmpty(records)) {
			return;
		}
		records.forEach(record -> {
			Integer orderStatus = gomeLuckPhoneHttpService.fetchOrderStatus(record.getOrderNo());
			if (orderStatus != null && !orderStatus.equals(record.getOrderStatus())) {
				UpdateWrapper updateWrapper = new UpdateWrapper();
				updateWrapper.eq("id", record.getId());
				updateWrapper.set("order_status", orderStatus);
				updateWrapper.set("update_time", System.currentTimeMillis());
				baseMapper.update(updateWrapper);
				statistics.put("update", statistics.get("update") + 1);
			}
		});
	}
}
